
import { EditOutlined, CheckOutlined, CloseOutlined } from '@ant-design/icons';
import { Avatar, Button, Input, Space, Select, DatePicker, Tooltip } from 'antd'
import { useEffect, useState, useMemo } from 'react';
import classNames from 'classnames';
import styles from './style.less';
import { connect } from 'umi';
import moment from 'moment';
import EnterpriseUserSelect from '@/components/EnterpriseUserSelect'
import { formetDate, parseDate } from '@/utils/dateUtils'
const { Option } = Select;
import EmptyContent from '@/components/EmptyContent'
const { RangePicker } = DatePicker;


const EditContent = (props) => {

    const {
        type,
        editComponentProps = {},
        editComponentClassName,
        onChange,
        onSave,
        onCancel,
        defaultValue,
        unSupportValue
    } = props

    const [realValue, setRealValue] = useState(defaultValue);
    const [controlData, setControlData] = useState();

    const onValueChangeEvent = (e) => {
        // console.log(e.target.value)
        setRealValue(e.target.value)
        if (onChange) {
            onChange(e.target.value)
        }
    }
    const onValueChange = (value, item) => {
        // console.log(value)
        setRealValue(value)
        if (onChange) {
            onChange(value, item)
        }
    }


    const onSaveClick = (value, item) => {
        // console.log(value,item)
        if (defaultValue === value) {
            onCancel()
            return;
        }
        if (onSave) {
            onSave(value || realValue, item)
        }
    }


    const className = editComponentClassName ? classNames(styles.defaultClass, editComponentClassName) : styles.defaultClass;
    if (type === "input") {
        return <Input {...editComponentProps} className={className} defaultValue={defaultValue} value={realValue}
            onChange={onValueChangeEvent}
            onPressEnter={() => onSaveClick()}
            onBlur={() => onSaveClick()} ></Input>
    } else if (type === "textarea") {
        return (<div>
            <Input.TextArea {...editComponentProps} className={className} defaultValue={defaultValue} onChange={onValueChangeEvent}></Input.TextArea>
            <Space align="center" style={{ marginTop: "8px" }}>
                <Button size="small" onClick={onCancel}>取消</Button>
                <Button type="primary" size="small" onClick={() => onSaveClick(realValue)}
                >保存</Button></Space>
        </div>)
    } else if (type === "select") {
        return (<div>
            <Select {...editComponentProps}
                onBlur={() => {
                    onSaveClick()
                }}
                defaultValue={defaultValue && `${defaultValue}`}
                className={className} onChange={(value) => {
                    onValueChange(value);
                    onSaveClick(value)
                }}>
            </Select>
        </div>)
    } else if (type === "userSelect") {
        return (
            <EnterpriseUserSelect
                {...editComponentProps}
                defaultValue={defaultValue && `${defaultValue}`}
                className={className}
                onBlur={() => {
                    onSaveClick()
                }}
                onChange={(value, item) => {
                    onValueChange(value, item);
                    onSaveClick(value, item)
                }}
            >
            </EnterpriseUserSelect>
        )
    } else if (type === "rangePicker") {
        return (
            <RangePicker
                {...editComponentProps}
                defaultValue={[parseDate(defaultValue[0]), parseDate(defaultValue[1])]}
                className={className}
                onBlur={() => {
                    // onSaveClick()
                }}
                showNow
                onCalendarChange={(dates, dateStrings, info) => {
                    // console.log('----', dates, dateStrings, info)
                    onValueChange([dates && formetDate(dates[0]), dates && formetDate(dates[1])]);
                    if (!dates) {
                        return;
                    }
                    let newControlData = controlData ? controlData + 1 : 1
                    if (newControlData === 2) {
                        if (dates[0] && dates[0]) {
                            setControlData(0)
                            onSaveClick([formetDate(dates[0]), formetDate(dates[1])])
                        } else {
                            setControlData(1)
                        }
                    } else {
                        setControlData(newControlData)
                    }
                }}
            >
            </RangePicker>
        )
    } else if (type === "timePicker") {
        return (
            <DatePicker
                {...editComponentProps}
                showTime={{ defaultValue: editComponentProps.defaultTime || moment('09:30:00', 'HH:mm:ss') }}
                showNow
                defaultValue={parseDate(defaultValue)}
                className={className}
                onBlur={() => {
                    // onSaveClick()
                }}
                onChange={(moment, value) => {
                    onValueChange(value);
                    onSaveClick(value)
                }}
            >
            </DatePicker>
        )
    }
    return <>{unSupportValue}</>;
}


const EditAble = (props) => {

    const {
        children,
        permission = {
            edit: true
        },
        value,
        // edit,
        type,
        isEdit,
        editComponent,
        editComponentProps = {},
        editComponentClassName,
        onChange,
        onSave,
        onCancel,
        onEdit,
        useCustomOperate = false,
        width,
    } = props

    const [editContent, setEditContent] = useState();
    const [isEditFalg, setIsEditFlag] = useState(false);
    const [realValueData, setRealValueData] = useState({});

    const useInnerFlag = () => {
        if (editComponent && !(isEdit === null || isEdit === undefined)) {
            return false
        }
        return true
    }

    const onSaveClick = (newValue, item) => {
        if (onSave && value !== newValue) {
            onSave(newValue, item)
        }
        // 新老值相等，取消逻辑
        if (onCancel && value === newValue) (
            onCancel()
        )
        if (useInnerFlag()) {
            setIsEditFlag(false)
        }
    }

    const onCancelClick = () => {
        if (onCancel) {
            onCancel()
        }
        if (useInnerFlag()) {
            setIsEditFlag(false)
        }
    }

    const onSaveIconClick = () => {
        console.log(realValueData)
        onSaveClick(realValueData?.value, realValueData?.item)
    }

    const onValueChange = (value, item) => {
        console.log(value, item)
        setRealValueData({
            value,
            item
        })
        if (onChange) {
            onChange(value, item)
        }
    }

    useEffect(() => {
        setIsEditFlag(isEdit)
        setRealValueData({
            value: value
        });
    }, [isEdit])


    useMemo(() => {
        if (isEditFalg) {
            if (editComponent) {
                setEditContent(editComponent);
            } else {
                setEditContent(<EditContent
                    type={type}
                    editComponentProps={editComponentProps}
                    editComponentClassName={editComponentClassName}
                    onChange={onValueChange}
                    onSave={onSaveClick}
                    onCancel={onCancelClick}
                    defaultValue={value}
                    unSupportValue={children}
                />)
            }
        }
    }, [isEditFalg])

    const onEditClick = () => {
        if (useInnerFlag()) {
            setIsEditFlag(true)
        } else {
            onEdit();
        }
    }

    const isInitNull = (value === undefined || value === null || value === "");
    if (permission.edit) {
        // console.log(value,isInitNull)
        return <div className={styles.canEditField} style={{
            width: width
        }}>
            {isEditFalg && editContent ?
                <>
                    {!useCustomOperate && (<>
                        <Avatar size={16} className={styles.saveIconClass} style={{ marginTop: "-5px" ,lineHeight:"14px"}} onClick={onSaveIconClick} icon={<CheckOutlined />} />
                        <Avatar size={16} className={styles.cancelIconClass} style={{ marginTop: "13px" ,lineHeight:"14px"}} onClick={onCancelClick} icon={<CloseOutlined />} />
                    </>)}
                    {editContent}
                </>
                :
                <>
                    <Avatar size={20} className={styles.editIconClass} style={{ marginTop: "0px" }} onClick={onEditClick} icon={<EditOutlined />} />
                    {isInitNull ? <EmptyContent text={'未设置'} onClick={onEditClick} ></EmptyContent> : children}
                </>
            }
        </div>
    }
    return (<div style={{
        width: width
    }}>{isInitNull ? <EmptyContent text={'未设置'}></EmptyContent> : children}</div>)


}

export default connect(({ }) => ({
}))(EditAble);